﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Kaleida.ServiceMonitor.Model;
using Kaleida.ServiceMonitor.Model.Runtime;

namespace Kaleida.ServiceMonitor.UI.NotificationPanels
{
    public partial class ResponsesNotificationPanel : UserControl, INotificationPanel
    {
        private Monitor monitor;

        public ResponsesNotificationPanel()
        {
            InitializeComponent();
        }

        public void Initialise(Monitor monitorApplication)
        {
            monitor = monitorApplication;
        }

        private LimitedList<RequestResult> DataSource
        {
            get { return chkErrorsOnly.Checked ? monitor.RecentErrors : monitor.RecentResponses; }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            DataSource.Items.Clear();
        }

        public string PanelName
        {
            get { return "Responses"; }
        }

        public Control GetPanelControl()
        {
            return this;
        }

        public void RefreshContent()
        {
            lblItemLimit.Text = DataSource.Summary();

            var source = GetDataSourceListCopy();

            lock (lbRecentRequests)
            {
                SyncListBox(source);
            }
            Invalidate();
        }


        private void SyncListBox(IList<RequestResult> dataSource)
        {
            var superfluousListItems = lbRecentRequests.Items.Cast<RequestResult>().Where(i => !dataSource.Contains(i)).ToList();

            foreach (var superfluousListItem in superfluousListItems)
            {
                lbRecentRequests.Items.Remove(superfluousListItem);
            }

            var missingListItems = dataSource.Where(i => !lbRecentRequests.Items.Contains(i));
            lbRecentRequests.Items.AddRange(missingListItems.Cast<object>().ToArray());
        }

        private void btnCopyToClipboard_Click(object sender, EventArgs e)
        {
            var source = GetDataSourceListCopy();

            var content = new StringBuilder("SentOn\tDuration\r\n");

            foreach (RequestResult result in source)
            {
                content.AppendLine(result.ToClipboardItemText());
            }
            
            Clipboard.SetText(content.ToString(), TextDataFormat.Text);
        }

        private IList<RequestResult> GetDataSourceListCopy()
        {
            lock (DataSource)
            {
                return DataSource.Items.ToList();
            }
        }
    }
}
